package com.bowlong.third.grizzly;

import java.io.DataOutput;
import java.io.IOException;
import java.io.OutputStream;

import org.glassfish.grizzly.Buffer;

public class GrizzlyOutputStream extends OutputStream implements DataOutput {

	final Buffer buffer;

	final byte TRUE = 1;
	final byte FALSE = 0;

	public GrizzlyOutputStream(Buffer buffer) {
		this.buffer = buffer;
	}

	@Override
	public void writeBoolean(boolean v) throws IOException {
		buffer.put(v ? TRUE : FALSE);
	}

	@Override
	public void writeByte(int v) throws IOException {
		byte b = (byte) v;
		buffer.put(b);
	}

	@Override
	public void writeShort(int v) throws IOException {
		short value = (short) v;
		buffer.putShort(value);
	}

	@Override
	public void writeChar(int v) throws IOException {
		char value = (char) v;
		buffer.putChar(value);
	}

	@Override
	public void writeInt(int v) throws IOException {
		buffer.putInt(v);
	}

	@Override
	public void writeLong(long v) throws IOException {
		buffer.putLong(v);
	}

	@Override
	public void writeFloat(float v) throws IOException {
		buffer.putFloat(v);
	}

	@Override
	public void writeDouble(double v) throws IOException {
		buffer.putDouble(v);
	}

	@Override
	public void writeBytes(String s) throws IOException {
		buffer.put8BitString(s);
	}

	@Override
	public void writeChars(String s) throws IOException {
		byte[] bs = s.getBytes();
		buffer.putInt(bs.length);
		buffer.put(bs);
	}

	@Override
	public void writeUTF(String s) throws IOException {
		byte[] bs = s.getBytes("UTF-8");
		buffer.putInt(bs.length);
		buffer.put(bs);
	}

	@Override
	public void write(int b) throws IOException {
		byte val = (byte) b;
		buffer.put(val);
	}

	public int postion() {
		return buffer.position();
	}

	public void postion(int pos) {
		buffer.position(pos);
	}

	@Override
	public void write(byte[] b) throws IOException {
		buffer.put(b);
	}

	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		buffer.put(b, off, len);
	}
	
}
